#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
策略参数设置对话框
"""
import logging
from typing import Any, Dict, Tuple

from PySide6.QtWidgets import QScrollArea, QWidget, QLabel

from ui.components.base.base_dialog import TgBaseDialog
from ui.components.composite.form_layout import TgFormLayout
from ui.components.buttons.button import TgButton
from ui.components.inputs.line_edit import TgLineEdit
from ui.components.layouts.vbox_layout import TgVBoxLayout
from ui.components.layouts.hbox_layout import TgHBoxLayout
from ui.components.dialogs.message_box import TgMessageBox


logger = logging.getLogger(__name__)


class StrategyParameterDialog(TgBaseDialog):
    """策略参数编辑对话框"""

    def __init__(self, strategy_name: str, parameters: Dict[str, Any], parent=None):
        # 策略名与默认参数
        self.strategy_name = strategy_name
        self.parameters = parameters or {}
        # 存储：输入框、类型、默认值
        self._editors: Dict[str, Tuple[TgLineEdit, type, Any]] = {}
        self._setting: Dict[str, Any] = {}
        super().__init__(parent)
        self.setWindowTitle(f"策略参数配置：{strategy_name}")
        self.resize(600, 500)

    def setup_ui(self) -> None:
        """构建UI"""
        try:
            main_layout = TgVBoxLayout(self)

            # 参数编辑表单（TgFormLayout 是 QWidget），放入滚动区域
            form_layout = TgFormLayout()

            for name, default_value in self.parameters.items():
                value_type = type(default_value)
                edit = TgLineEdit(str(default_value))

                # 数值类型加校验器（尽量不干扰用户输入）
                try:
                    if value_type is int:
                        from PySide6.QtGui import QIntValidator
                        edit.setValidator(QIntValidator())
                    elif value_type is float:
                        from PySide6.QtGui import QDoubleValidator
                        edit.setValidator(QDoubleValidator())
                except Exception as e:
                    # 校验器失败仅记录
                    logger.exception(e)

                form_layout.add_row(f"{name} ({value_type.__name__})", edit)
                self._editors[name] = (edit, value_type, default_value)

            scroll = QScrollArea()
            scroll.setWidgetResizable(True)
            scroll.setWidget(form_layout)

            main_layout.addWidget(scroll)

            # 按钮区
            button_layout = TgHBoxLayout()
            button_layout.addStretch()
            ok_btn = TgButton("确定", theme="primary")
            cancel_btn = TgButton("取消", theme="secondary")
            ok_btn.clicked.connect(self._on_confirm)
            cancel_btn.clicked.connect(self.reject)
            button_layout.addWidget(ok_btn)
            button_layout.addWidget(cancel_btn)
            main_layout.addLayout(button_layout)
        except Exception as e:
            # 构建UI异常
            logger.exception(e)
            TgMessageBox.warning(self, "错误", f"构建参数对话框时发生错误: {e}")

    def _on_confirm(self) -> None:
        """确认收集参数"""
        try:
            setting: Dict[str, Any] = {}
            for name, (editor, value_type, default_value) in self._editors.items():
                raw_text = editor.text()
                text = raw_text.strip() if isinstance(raw_text, str) else raw_text

                try:
                    if value_type is bool:
                        # 允许多种布尔写法；空时回退默认
                        if text == "":
                            value = bool(default_value)
                        else:
                            lowered = str(text).lower()
                            if lowered in ("true", "1", "yes", "y", "t"):
                                value = True
                            elif lowered in ("false", "0", "no", "n", "f"):
                                value = False
                            else:
                                raise ValueError(f"{name}: 无法解析布尔值 '{text}'")
                    elif value_type in (int, float):
                        # 数值空输入 -> 使用默认值
                        if text == "":
                            value = default_value
                        else:
                            value = value_type(text)
                    else:
                        # 其它类型允许空字符串，空时回退默认
                        value = text if text != "" else default_value
                except ValueError as ve:
                    # 针对字段的具体报错，并保持对话框不关闭
                    logger.exception(ve)
                    TgMessageBox.warning(self, "参数错误", f"字段 '{name}' 的输入无效: {ve}")
                    return

                setting[name] = value

            self._setting = setting
            self.accept()
        except Exception as e:
            logger.exception(e)
            TgMessageBox.warning(self, "错误", f"读取参数时发生错误: {e}")

    def get_setting(self) -> Dict[str, Any]:
        """返回用户编辑后的参数设置"""
        return self._setting or {}

